package handlers

import (
	"fmt"
	"golang-master/photo-gallery/models"
	"golang-master/photo-gallery/utils"
	"log"
	"net/http"
	"path/filepath"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type ImageHandler struct {
	DB *gorm.DB
}

func NewImageHandler(db *gorm.DB) *ImageHandler {
	return &ImageHandler{DB: db}
}

func (h *ImageHandler) UploadImage(c *gin.Context) {
	userID := c.MustGet("user_id").(uint)

	title := c.PostForm("title")
	categoryIDStr := c.PostForm("category_id")
	tagIDsStr := c.PostFormArray("tag_ids")

	file, err := c.FormFile("image")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "No image file provided"})
		return
	}

	// 验证文件类型
	ext := filepath.Ext(file.Filename)
	allowedExtensions := map[string]bool{
		".jpg": true, ".jpeg": true, ".png": true, ".gif": true,
	}

	if !allowedExtensions[ext] {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid file type. Only JPG, PNG and GIF are allowed"})
		return
	}

	// 保存文件
	timestamp := time.Now().Format("20060102150405")
	filename := fmt.Sprintf("%d_%s_%s", userID, timestamp, file.Filename)
	if err := c.SaveUploadedFile(file, filepath.Join("photo-gallery/static/uploads", filename)); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save file"})
		return
	}

	// 创建图片记录
	image := models.Image{
		Title:    title,
		Filename: filename,
		UserID:   userID,
	}

	if categoryIDStr != "" {
		if categoryID, err := strconv.ParseUint(categoryIDStr, 10, 32); err == nil {
			categoryIDUint := uint(categoryID)
			image.CategoryID = &categoryIDUint
		}
	}

	if err := h.DB.Create(&image).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save image record"})
		return
	}

	// 处理标签关联
	if len(tagIDsStr) > 0 {
		for _, tagIDStr := range tagIDsStr {
			if tagID, err := strconv.ParseUint(tagIDStr, 10, 32); err == nil {
				var tag models.Tag
				if err := h.DB.First(&tag, tagID).Error; err == nil && tag.UserID == userID {
					h.DB.Model(&image).Association("Tags").Append(&tag)
				}
			}
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "Image uploaded successfully",
		"image":   image,
	})
}

func (h *ImageHandler) GetImages(c *gin.Context) {
	userID := c.MustGet("user_id").(uint)

	var images []models.Image
	query := h.DB.Preload("User").Preload("Category").Preload("Tags").Where("user_id = ?", userID)

	// 按名称搜索
	if name := c.Query("name"); name != "" {
		query = query.Where("title LIKE ?", "%"+name+"%")
	}

	// 按分类筛选
	if categoryID := c.Query("category_id"); categoryID != "" {
		query = query.Where("category_id = ?", categoryID)
	}

	// 按标签筛选
	if tagID := c.Query("tag_id"); tagID != "" {
		query = query.Joins("JOIN image_tags ON images.id = image_tags.image_id").
			Where("image_tags.tag_id = ?", tagID)
	}

	query.Find(&images)

	c.JSON(http.StatusOK, images)
}

func (h *ImageHandler) DeleteImage(c *gin.Context) {
	userID := c.MustGet("user_id").(uint)
	imageID := c.Param("id")

	var image models.Image
	if err := h.DB.Where("id = ? AND user_id = ?", imageID, userID).First(&image).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Image not found"})
		return
	}
	log.Println(image)

	// 删除数据库记录
	if err := h.DB.Delete(&image).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete image"})
		return
	}

	// 删除文件
	DeleteFile(filepath.Join("photo-gallery/static/uploads", image.Filename))

	c.JSON(http.StatusOK, gin.H{"message": "Image deleted successfully"})
}

func DeleteFile(fileNamePath string) {
	utils.DeleteFile(fileNamePath)

}
